package org.fatmansoft.teach.service;

import org.fatmansoft.teach.models.DailyActivity;
import org.fatmansoft.teach.models.Student;
import org.fatmansoft.teach.models.StudentDailyActivity;
import org.fatmansoft.teach.models.User;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.DailyActivityRepository;
import org.fatmansoft.teach.repository.StudentDailyActivityRepository;
import org.fatmansoft.teach.repository.StudentRepository;
import org.fatmansoft.teach.repository.UserRepository;
import org.fatmansoft.teach.util.CommonMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DailyActivityService {

    @Autowired
    DailyActivityRepository dailyActivityRepository;
    @Autowired
    StudentDailyActivityRepository studentDailyActivityRepository;
    @Autowired
    StudentRepository studentRepository;
    @Autowired
    UserRepository userRepository;

    /**************************************辅助方法*********************************************/

    //用于主键自增
    public synchronized Integer getNewDailyActivityId() {
        Integer id = dailyActivityRepository.getMaxId();
        if(id == null)
            id = 1;
        else
            id = id +1;
        return id;
    }

    public synchronized  Integer getNewStudentDailyActivityId() {
        Integer id = studentDailyActivityRepository.getMaxId();
        if(id == null)
            id = 1;
        else
            id = id + 1;
        return id;
    }

    //获取Student实体
    public Student getStudent(Integer studentId) {

        Student student = null;
        if(studentId != null) {
            Optional<Student> x1 = studentRepository.findById(studentId);
            if(x1.isPresent()) {
                student = x1.get();
            }
        }

        return student;
    }

    public Student getStudentByNum(String num) {
        Student student = null;
        if(num != null) {
            Optional<Student> x = studentRepository.findByPersonNum(num);
            if(x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }

    public User getUser(Integer id) {
        User user = null;
        if(id != null) {
            Optional<User> x = userRepository.findById(id);
            if(x.isPresent()) {
                user = x.get();
            }
        }
        return user;
    }

    public Student getStudentByPersonId(Integer id) {
        Student student = null;
        if(id != null) {
            Optional<Student> x = studentRepository.findByPersonPersonId(id);
            if(x.isPresent()) {
                student = x.get();
            }
        }
        return student;
    }

    public Student getLoginStudent() {
        Integer userId = CommonMethod.getUserId();
        Student student = null;

        User user = getUser(userId);
        if(user != null) {
            Integer personId = user.getPerson().getPersonId();
            student = getStudentByPersonId(personId);
        }

        return student;
    }

    public DailyActivity getDailyActivityByActivityName(String name) {
        DailyActivity dailyActivity = null;
        if(name != null) {
            Optional<DailyActivity> x = dailyActivityRepository.findByActivityName(name);
            if(x.isPresent()) {
                dailyActivity = x.get();
            }
        }
        return dailyActivity;
    }

    public Map getMapFromDaily(DailyActivity daily) {
        Map m = new HashMap();
        if(daily == null) {
            return m;
        }

        m.put("dailyActivityId",daily.getDailyActivityId());
        m.put("dailyActivityName",daily.getActivityName());
        m.put("dailyActivityType",daily.getActivityType());

        return m;
    }

    public List getDailyMapList(String nameType) {
        List dataList = new ArrayList();
        List<DailyActivity> dailyActivityList = dailyActivityRepository.findDailyListByNameType(nameType);
        if(dailyActivityList == null || dailyActivityList.size() == 0) {
            return dataList;
        }

        for(int i = 0;i < dailyActivityList.size();i++) {
            dataList.add(getMapFromDaily(dailyActivityList.get(i)));
        }

        return dataList;
    }

    public Map getMapFromStudentDaily(StudentDailyActivity studentDailyActivity){
        Student student = studentDailyActivity.getStudent();
        DailyActivity dailyActivity = studentDailyActivity.getDailyActivity();
        Map m = new HashMap<>();
        m.put("num",student.getPerson().getNum());
        m.put("name",student.getPerson().getName());
        m.put("activity",dailyActivity.getActivityName());
        m.put("type",dailyActivity.getActivityType());
        return m;
    }


    /********************************************接口业务逻辑部分****************************************/

    //插入新实体  ----------增
    public DataResponse saveActivity(DataRequest dataRequest) {

        //获取数据
        String activityName = dataRequest.getString("activityName");
        String activityType = dataRequest.getString("activityType");

        DailyActivity dailyActivity = getDailyActivityByActivityName(activityName);
        if(dailyActivity == null) {
            dailyActivity = new DailyActivity();
            dailyActivity.setDailyActivityId(getNewDailyActivityId());
        }
        dailyActivity.setActivityName(activityName);
        dailyActivity.setActivityType(activityType);

        dailyActivityRepository.save(dailyActivity);

        return CommonMethod.getReturnMessageOK();
    }

    //删除实体  -----------删
    @Transactional
    public DataResponse deleteActivity(DataRequest dataRequest) {

        //获取数据
        String name = dataRequest.getString("dailyActivityName");

        DailyActivity dailyActivity = getDailyActivityByActivityName(name);
        if (dailyActivity == null)
            return CommonMethod.getReturnMessageError("没有该日常活动！");
        //删除
        dailyActivityRepository.deleteByActivityName(name);

        return CommonMethod.getReturnMessageOK();
    }

    //更新实体  ------------改
    public DataResponse update(DataRequest dataRequest) {

        //获取数据
        Integer id = dataRequest.getInteger("dailyActivityId");
        String activityName = dataRequest.getString("activityName");
        String activityType = dataRequest.getString("activityType");

        //构造
        DailyActivity dailyActivity = new DailyActivity();
        dailyActivity.setDailyActivityId(id);
        dailyActivity.setActivityName(activityName);
        dailyActivity.setActivityType(activityType);

        //更新
        dailyActivityRepository.save(dailyActivity);

        return CommonMethod.getReturnMessageOK();
    }

    //查找单个实体 -----------查
    public DataResponse getDailyActivityInfo(DataRequest dataRequest) {

        //获取数据
        String name = dataRequest.getString("dailyActivityName");

        //查找
        DailyActivity dailyActivity = getDailyActivityByActivityName(name);

        if(dailyActivity == null) {
            return CommonMethod.getReturnMessageError("该日常活动不存在！");
        }

        return CommonMethod.getReturnData(getMapFromDaily(dailyActivity));
    }

    public DataResponse findByNameType(DataRequest dataRequest) {
        String nameType = dataRequest.getString("nameType");
        List datalist = getDailyMapList(nameType);
        return CommonMethod.getReturnData(datalist);
    }

    /**************************************中间表部分*********************************************/

    //插入中间表
    public DataResponse insertPlus(DataRequest dataRequest) {

        //获取数据
        String studentNum = dataRequest.getString("num");
        String dailyActivityName = dataRequest.getString("activityName");
        Student student = getStudentByNum(studentNum);
        DailyActivity dailyActivity = getDailyActivityByActivityName(dailyActivityName);

        if(student == null)
            return CommonMethod.getReturnMessageError("学生不存在！");
        if(dailyActivity == null)
            return CommonMethod.getReturnMessageError("该日常活动不存在！");

        StudentDailyActivity x = studentDailyActivityRepository.findStudentDailyActivityByStudentAndDailyActivity(student,dailyActivity);
        if(x != null) {
            return CommonMethod.getReturnMessageError("该学生已有该活动！");
        }
        //构建新实体
        StudentDailyActivity studentDailyActivity = new StudentDailyActivity();
        studentDailyActivity.setStudentDailyActivityId(getNewStudentDailyActivityId());
        studentDailyActivity.setStudent(student);
        studentDailyActivity.setDailyActivity(dailyActivity);

        //插入表中
        studentDailyActivityRepository.save(studentDailyActivity);

        return CommonMethod.getReturnMessageOK();
    }

    //删除中间表的一项
    @Transactional
    public DataResponse deleteStudentDailyActivity(DataRequest dataRequest) {
        String num = dataRequest.getString("num");
        String daily = dataRequest.getString("daily");
        Student student = getStudentByNum(num);
        DailyActivity dailyActivity = getDailyActivityByActivityName(daily);
        studentDailyActivityRepository.deleteByStudentAndDailyActivity(student, dailyActivity);

        return CommonMethod.getReturnMessageOK();
    }

    //查找一个学生所有DailyActivity
    public DataResponse getDailyActivityByStudent(DataRequest dataRequest) {

        //获取数据
        Integer studentId = dataRequest.getInteger("studentId");

        //查找Student实体
        Student student = getStudent(studentId);

        if(student != null) {
            return CommonMethod.getReturnData(new ArrayList<>(student.getDailyActivities())); //打包成列表返回
        }
        else {
            return CommonMethod.getReturnMessageError("学生不存在！");
        }

    }

    public DataResponse getStudentDailyActivityList(DataRequest dataRequest) {
        List dataList = new ArrayList<>();
        String studentDaily = dataRequest.getString("studentDaily");
        List<StudentDailyActivity> sList = studentDailyActivityRepository.findByStudentDaily(studentDaily);
        if(sList == null || sList.size() == 0)
            return CommonMethod.getReturnData(dataList);
        for(int i = 0;i < sList.size();i++) {
            dataList.add(getMapFromStudentDaily(sList.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }

    public DataResponse getStudentDailyActivityListByStudent(DataRequest dataRequest) {
        Student student = getLoginStudent();
        List dataList = new ArrayList<>();
        List<StudentDailyActivity> studentDailyActivities = studentDailyActivityRepository.findByStudentDaily(student.getPerson().getName());
        if(studentDailyActivities == null || studentDailyActivities.size() == 0)
            return CommonMethod.getReturnData(dataList);
        for(int i = 0;i < studentDailyActivities.size();i++) {
            dataList.add(getMapFromStudentDaily(studentDailyActivities.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }

    public DataResponse getStudentDailyActivityByStudentAndDaily(DataRequest dataRequest) {
        Student student = getLoginStudent();
        String studentDaily = dataRequest.getString("studentDaily");
        String studentNum = student.getPerson().getNum();
        List dataList = new ArrayList<>();
        List<StudentDailyActivity> studentDailyActivities = studentDailyActivityRepository.findByStudentPersonNumAndDailyActivityActivityName(studentNum, studentDaily);
        if(studentDailyActivities == null || studentDailyActivities.size() == 0)
            return CommonMethod.getReturnData(dataList);
        for(int i = 0;i < studentDailyActivities.size();i++) {
            dataList.add(getMapFromStudentDaily(studentDailyActivities.get(i)));
        }
        return CommonMethod.getReturnData(dataList);
    }
}
